﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Top.Api;
using System.Configuration;
using Collection.Interfaces;
namespace Collection.Core
{
	public class CollectorBase
	{
		/// <summary>
		/// 应用Key表示
		/// </summary>
		private static String[] keys;

		/// <summary>
		/// 密钥
		/// </summary>
		private static String[] secrets;

		/// <summary>
		/// 选择Key和密钥的指针
		/// </summary>
		private static UInt16 pointer;

		/// <summary>
		/// 属性路径格式
		/// </summary>
		private static string pathFormat;

		/// <summary>
		/// 淘宝api地址
		/// </summary>
		private static string apiUrl;

		/// <summary>
		/// 佣金收入账号
		/// </summary>
		private static string nick;

		/// <summary>
		/// 在静态函数中初始化其静态的淘宝api
		/// </summary>
		static CollectorBase()
		{
			pathFormat = ConfigurationManager.AppSettings["pathFormat"];
			apiUrl = ConfigurationManager.AppSettings["apiUrl"];
			nick = ConfigurationManager.AppSettings["nick"];
			keys = ConfigurationManager.AppSettings["appKey"].Split(';');
			secrets = ConfigurationManager.AppSettings["secret"].Split(';');
			pointer = UInt16.MinValue;
		}

		/// <summary>
		/// 属性路径格式
		/// </summary>
		protected static String PathFormat
		{
			get { return pathFormat; }
		}

		/// <summary>
		/// 淘宝api的Url
		/// </summary>
		protected static String ApiUrl
		{
			get
			{
				return apiUrl;
			}
		}

		/// <summary>
		/// 获取佣金的淘宝账号
		/// </summary>
		protected static String Nick
		{
			get { return nick; }
		}

		/// <summary>
		/// 供外部（子类）获取的淘宝api接口
		/// </summary>
		public static ITopClient TaobaoApi
		{
			get
			{
				var _pointer = SwitchAppKey();
				return new DefaultTopClient(ApiUrl, keys[_pointer], secrets[_pointer]);
			}
		}

		/// <summary>
		/// 切换appk指针
		/// </summary>
		/// <returns></returns>
		private static UInt16 SwitchAppKey()
		{
			pointer++;
			if (pointer == keys.Length) pointer = UInt16.MinValue;
			return pointer;
		}

		/// <summary>
		/// 创建属性查询路径
		/// </summary>
		/// <param name="property"></param>
		/// <param name="value"></param>
		/// <returns></returns>
		public static String CreatePath(Int64 property, Int64 value)
		{
			return String.Format(PathFormat, property, value);
		}
	}
}
